package org.luckyjourney.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class UtilClass {
    /**
     * 获取openid和session_key
     *
     * @param code      由前端传值
     * @param appId
     * @param appSecret
     * @return
     */
    public static JSONObject getOpenIdAndSessionKey(String code, String appId, String appSecret) {
        JSONObject jsonObject = null;
        try {
            // 请求微信接口获取openid和session_key
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + appId +
                    "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code";

            HttpClient httpClient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpClient.execute(httpGet);
            String jsonString = EntityUtils.toString(response.getEntity());

            jsonObject = JSONObject.parseObject(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
}
